<?php
/**
 * @project kkzc
 * @date 2015-7-23
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\module\api\controllers;


use app\models\ApplyRequest;
use app\services\PromoteService;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\Cors;
use yii\helpers\Json;
use yii\rest\Controller;

/**
 * 推广
 * @author xialei <xialeistudio@gmail.com>
 * Class PromoteController
 * @package app\module\api\controllers
 */
class PromoteController extends Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['corsFilter'] = [
            'class' => Cors::className()
        ];
        if (!\Yii::$app->request->isOptions) {
            $behaviors['authenticator'] = [
                'class' => HttpBearerAuth::className()
            ];
        }
        return $behaviors;
    }

    /**
     * 下线
     * @author xialei <xialeistudio@gmail.com>
     */
    public function actionReferrals()
    {
        $uid = \Yii::$app->user->id;
        $data = PromoteService::instance()->getReferralsCount($uid);
        echo Json::encode($data);
    }

    /**
     * 租客
     * @author xialei <xialeistudio@gmail.com>
     */
    public function actionTenants()
    {
        $uid = \Yii::$app->user->id;

        $data = PromoteService::instance()->getTenants($uid);
        echo Json::encode($data);
    }

    /**
     * 车主
     * @author xialei <xialeistudio@gmail.com>
     */
    public function actionOwner()
    {
        $uid = \Yii::$app->user->id;

        $data = PromoteService::instance()->getOwners($uid);
        echo Json::encode($data);
    }

    /**
     * 订单数量统计
     * @author xialei <xialeistudio@gmail.com>
     * @param int $day
     * @throws \yii\base\Exception
     */
    public function actionOrder($day = 7)
    {
        $uid = \Yii::$app->user->id;
        $data = PromoteService::instance()->getOrderCount($uid, $day);
        echo Json::encode($data);
    }

    /**
     * 提现金额统计
     * @author xialei <xialeistudio@gmail.com>
     * @param $state
     */
    public function actionRequestsum($state)
    {
        $data = ApplyRequest::find()->where(['user_id' => \Yii::$app->user->id, 'state' => $state])->sum('amounts');
        echo Json::encode([
            'amounts' => intval($data)
        ]);
    }

    /**
     * 注册起X天内车次
     * @author xialei <xialeistudio@gmail.com>
     * @param int $day
     */
    public function actionTrains($day = 7)
    {
        $data = PromoteService::instance()->getTrains(\Yii::$app->user->id, $day);
        echo Json::encode($data);
    }

    /**
     * 排行版
     * @author xialei <xialeistudio@gmail.com>
     */
    public function actionRank()
    {
        $data = PromoteService::instance()->rank();
        echo Json::encode($data);
    }
}